package com.kung.qvs.ui.main.fragment;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;

import com.kung.qvs.BR;
import com.kung.qvs.R;
import com.kung.qvs.data.JtRepository;
import com.kung.qvs.entity.BaseResultBean;
import com.kung.qvs.entity.KRecordWeight;
import com.kung.qvs.entity.PrintDataBean;
import com.kung.qvs.entity.ProductBean;
import com.kung.qvs.entity.SpinnerItemData;
import com.kung.qvs.entity.database.SqlManager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.binding.command.BindingConsumer;
import me.goldze.mvvmhabit.binding.viewadapter.spinner.IKeyAndValue;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.http.ResponseThrowable;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;

public class CollectTrashRecordViewModel extends BaseViewModel<JtRepository> {

    private List<PrintDataBean> trashDataBeans = new ArrayList<>();
    //合计
    public ObservableField<String> mWeight = new ObservableField<>("0.00");    //总重量
    public ObservableField<String> mCount = new ObservableField<>("0");    //收集筐数
    public ObservableField<String> mAmount = new ObservableField<>("0.00");    //总数量
    public ObservableField<String> mStartDate = new ObservableField<>();
    public ObservableField<String> mEndDate = new ObservableField<>();

    public ObservableField<Integer> pageSizes = new ObservableField<>(100);
    public ObservableField<Integer> pageIndex = new ObservableField<>(1);

    public List<IKeyAndValue> productItemDatas;
    public ObservableField<String> mProductName = new ObservableField<>();

    SimpleDateFormat kjdf2 = new SimpleDateFormat("yyyy-MM-dd");  //设置日期格式

    //封装一个界面发生改变的观察者
    public UIChangeObservable uc = new UIChangeObservable();
    public class UIChangeObservable {
        //下拉刷新完成
        public SingleLiveEvent finishRefreshing = new SingleLiveEvent<>();
        //上拉加载完成
        public SingleLiveEvent finishLoadmore = new SingleLiveEvent<>();

        public SingleLiveEvent eventToBack = new SingleLiveEvent<>();
        public SingleLiveEvent<String> eventChangeTrashType = new SingleLiveEvent<>();
        public SingleLiveEvent<KRecordWeight> eventPrintItem = new SingleLiveEvent<>();
        public SingleLiveEvent eventStartSync = new SingleLiveEvent();

        public SingleLiveEvent eventDateStart = new SingleLiveEvent();
        public SingleLiveEvent eventDateEnd = new SingleLiveEvent();
    }

    public CollectTrashRecordViewModel(@NonNull Application application, JtRepository model) {
        super(application, model);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //获取当前日期
        mStartDate.set(kjdf2.format(new java.util.Date()));
        mEndDate.set(kjdf2.format(new java.util.Date()));

        List<String> lt = SqlManager.getPrintDataProducts(model.getEquipmentNo());
        productItemDatas = new ArrayList<>();
        productItemDatas.add(new SpinnerItemData("全部", "全部"));
        for (int i = 0; i < lt.size(); i++) {
            productItemDatas.add(new SpinnerItemData(lt.get(i), lt.get(i)));
        }
    }

    //性别选择的监听
    public BindingCommand<IKeyAndValue> onSelectorCommand = new BindingCommand<>(new BindingConsumer<IKeyAndValue>() {
        @Override
        public void call(IKeyAndValue iKeyAndValue) {
            mProductName.set(iKeyAndValue.getValue());
        }
    });


    public BindingCommand onSyncTrashData = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
//            //将本地垃圾状态进行修改 将本地数据状态修改，然后执行上传
//            SqlManager.updateCollectTrashFst(model.getEquipmentNo(), "0", "1");
//            uc.eventStartSync.call();
            //查询数据
            pageIndex.set(1);
            doGetTrashDataBeans();
        }
    });

    //返回称重页面
    public BindingCommand onBackWeigh = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.eventToBack.call();
        }
    });

    public BindingCommand onCommandDateStart = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.eventDateStart.call();
        }
    });

    public BindingCommand onCommandDateEnd = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.eventDateEnd.call();
        }
    });

    //下拉刷新
    public BindingCommand onRefreshCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            pageIndex.set(1);
            uc.finishRefreshing.call();
        }
    });
    //上拉加载
    public BindingCommand onLoadMoreCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.finishLoadmore.call();
        }
    });

    //给RecyclerView添加ObservableList
    public ObservableList<CollectTrashRecordItemViewModel> observableList = new ObservableArrayList<>();
    //给RecyclerView添加ItemBinding
    public ItemBinding<CollectTrashRecordItemViewModel> itemBinding = ItemBinding.of(BR.viewModel, R.layout.item_collect_trash_record);



    public void doGetTrashDataBeans() {
        String beginDate;
        String endDate;
        String type;
        if (StringUtils.isTrimEmpty(mStartDate.get())) {
            beginDate = "";
        } else {
            beginDate = mStartDate.get() + " 00:00:00";
        }

        if (StringUtils.isTrimEmpty(mEndDate.get())) {
            endDate = "";
        } else {
            endDate = mEndDate.get() + " 23:59:59";
        }
        if ("全部".equals(mProductName.get())) {
            type = "";
        } else {
            type = mProductName.get();
        }

        //清除列表
        if (pageIndex.get() == 1) {
            observableList.clear();
            mWeight.set("0.00");
            mCount.set("0");
            mAmount.set("0");
        }

        model.reqGetWeightRecord("", model.getEquipmentNo(), "", beginDate, endDate, pageSizes.get(), pageIndex.get()).compose(RxUtils.schedulersTransformer()) //线程调度
                .compose(RxUtils.exceptionTransformer()) // 网络错误的异常转换, 这里可以换成自己的ExceptionHandle
                .doOnSubscribe(this)//请求与ViewModel周期同步
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
//                        showDialog("正在请求数据...");
                    }
                })
                .subscribe(new DisposableObserver<BaseResultBean<List<KRecordWeight>>>() {
                    @Override
                    public void onNext(BaseResultBean<List<KRecordWeight>> response) {
                        //请求成功
                        if (response.isSuccess()) {
                            //数据插入本地，并根据id排序查询。已被无网络情况使用
                            if (response.entity == null || response.entity.size() < 1) {
                                return;
                            }
                            pageIndex.set(pageIndex.get() + 1);
                            double totalWeight = mWeight.get() == null ? 0.0 : Double.parseDouble(mWeight.get());
                            int num = mAmount.get() == null ? 0 : Integer.parseInt(mAmount.get());
                            int index = 0;
                            for (KRecordWeight bean : response.entity) {
                                bean.setIndex((index + 1) + "");
                                index++;
                                observableList.add(new CollectTrashRecordItemViewModel(CollectTrashRecordViewModel.this, bean));
                                totalWeight = totalWeight + Double.parseDouble(bean.getWeight());
                                num = num + Integer.parseInt(bean.getAmount());
                            }
                            mWeight.set(String.format("%.2f", totalWeight));
                            mCount.set(observableList.size() + "");
                            mAmount.set(num + "");
                        } else {
                            //code错误时也可以定义Observable回调到View层去处理
//                            ToastUtils.showShort(response.getErrorMsg());
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        //关闭对话框
//                        dismissDialog();
                        if (throwable instanceof java.util.concurrent.TimeoutException) {

                        } else if (throwable instanceof ResponseThrowable) {
                            ToastUtils.showShort(((ResponseThrowable) throwable).message);
                            //token失效，重新登录
//                            finish();
                            //如果无网络，使用本地缓存垃圾分类
                        }
                    }

                    @Override
                    public void onComplete() {
                        //关闭对话框
//                        dismissDialog();
                    }
                });
    }
}
